<?php


namespace app\xiangji\jobs;


use app\common\models\LoveAchieve;
use app\common\models\User;
use app\xiangji\services\LoveAchieveService;
use think\facade\Log;
use think\queue\Job;

class AchieveLoveScoreJob
{
    public function fire(Job $job, array $data)
    {
        try {
            $user = User::where('id', '=', $data['user_id'])->find();
            if (!$user) {
                $job->delete();
                return;
            }
            if ($job->attempts() >= 3){
                $job->delete();
                return;
            }
            switch ($data['type']){
                case LoveAchieve::TYPE_SIGN:
                    $level = $user->signs()->where('sign_status', '>', 0)->count('id');
                    break;
                case LoveAchieve::TYPE_DIARY:
                    $level = $user->diaries()->count('id');
                    break;
                case LoveAchieve::TYPE_ANNIVERSARY:
                    $level = $user->anniversaries()->count('id');
                    break;
            }
            LoveAchieveService::addAchieve($user, $data['type'], $level);
            $job->delete();
            return true;
        } catch (\Exception $exception){
            Log::error('恩爱值成就触发错误', [
                'data' => $data,
                'error' => $exception
            ]);
            $job->delete();
        }
    }
}
